<script lang="ts" setup>
import Header from "../components/Header.vue";

import {useStore} from "vuex"
import user from '../api/user'
import {useRouter} from "vue-router"
import login from "../api/login";
import {Delete, InfoFilled} from '@element-plus/icons-vue'

const router = useRouter()

const store = useStore()

import {ref, watch} from 'vue'
import {ElMessage,} from "element-plus";
import funcs from '../utils/func'


// 展示头像

const showPreview = () => {
  user.uploadDialogVisible = true
}
console.log()
// 编辑资料
const userData = () => {
  const token = sessionStorage.getItem("token") || localStorage.getItem("token");
  if (!token) {
    ElMessage.error("请先登录！");
    router.push("/login");
    login.is_register = false
  }
  user.userData(token, store.state.user.user_id).then((res) => {
    ElMessage.success("编辑成功！");
    user.editDataFormVisible = false
    getUserInfo()
    // todo header更新头像
    console.log(res)
  }).catch((err) => {
    ElMessage.error("编辑失败！");
    console.log(err)
  })
}

// 上传头像成功后，地址
const successImg = (res) => {
  user.userForm.avatar = res.imgPath
}

// 获取用户信息
const getUserInfo = () => {
  user.getUserInfo(store.state.user.user_id).then((res) => {
    // user.avatar = res.data.avatar
    console.log(res.data.avatar)
    user.aliyunAvatar = res.data.avatar
    store.commit('showImg', res.data.avatar)
    store.commit('showImgLocal', 'http://api.leleapi.cn:8000/uploads/' + res.data.avatar.split('uploads/')[1])
    const avatar_list = res.data.avatar.split('/')
    user.userForm.avatar = avatar_list[avatar_list.length - 1]
    user.userForm.nickname = res.data.nickname
    user.userForm.gender = String(res.data.gender)
    user.userForm.signature = res.data.signature
    user.userForm.is_show = funcs.changeType(res.data.is_show)
  })
}
getUserInfo()


// 查询所有帖子
const getArticles = () => {
  user.getListArticle(store.state.user.user_id).then((res) => {
    user.articleList = res.data
  })
}
getArticles()

// 显示文章是否显示个人信息
const showDialogVisible = (item) => {
  user.showVisible = true
  user.articleShow = '3'
  user.articleShow = funcs.changeType(item.is_show)
  user.articleID = item.id
}

// 确认修改文章是否显示个人信息
const confirmEditIsShow = () => {
  user.editIsShow(user.articleID).then(() => {
    ElMessage.success("修改成功！");
    //   更新传过来的user.articleList
    getArticles()
  }).catch(() => {
    ElMessage.error("修改失败！");
  })
  user.showVisible = false
}

const loadError = (path) => {
  user.articleIMG = user.b
}

// 加载头像失败
const errorAvatar = () => {
  user.aliyunAvatar = store.state.imgAPI
}

// 删除文章
const confirmDelete = (id) => {
  user.confirmDelete(id).then(() => {
    ElMessage.success("删除成功！");
    //   更新传过来的user.articleList
    getArticles()
  }).catch(() => {
    ElMessage.error("删除失败！");
  })
}

// 点击放大图片
const showBigImg = (src) => {
  user.avatarStatus = true
  user.bigImg = src
}

// 放大图片错误
const bigImgError = () => {
  user.bigImg = 'http://api.leleapi.cn:8000/uploads/' +  user.bigImg.split('uploads/')[1]
}
</script>

<template>
  <link rel="stylesheet" href="../../iconfont.css">
  <link rel="stylesheet" href="../../icon/collect/iconfont.css">
  <link rel="stylesheet" href="../../icon/change/iconfont.css">
  <Header></Header>
  <div style="height: 700px;">
    <div class="wrapper" style="padding: 20px;">
      <div class="data">
        <el-avatar :size="100" :src="user.aliyunAvatar"
                   @click="showBigImg(user.aliyunAvatar)" @error="errorAvatar"/>
        <div class="info">
          <span class="nickname" v-if="user.userForm.nickname">{{ user.userForm.nickname }}</span>
          <span class="nickname" v-else>未设置昵称</span>
          <!--          <div class="email">{{store.state.user.email}}</div>-->
          <div class="friends">朋友 &nbsp;&nbsp;<span>10</span></div>
          <div class="signature">个性签名：
            <el-tooltip v-if="user.userForm.signature" :content="user.userForm.signature" placement="bottom"
                        effect="light">
              {{ user.userForm.signature }}
            </el-tooltip>
            <el-tooltip v-else content="暂无个性签名" placement="bottom" effect="light">
              快快动动你的小手，添加个性签名吧！
            </el-tooltip>
          </div>
        </div>
      </div>
       <el-dialog
        v-model="user.avatarStatus"
        align-center
       >
        <el-image :src="user.bigImg" @error="bigImgError"/>
     </el-dialog>
      <div class="edit_info">
        <el-button type="info" @click="user.editDataFormVisible=true">编辑资料</el-button>
      </div>
      <div>
        <el-tabs type="border-card" style="margin-top: 40px;">
          <el-tab-pane label="发表">
            <el-card style="min-width: 250px;margin-bottom: 20px;float: left;margin-right: 20px;position: relative;"
                     v-for="(item, index) in user.articleList" :key="index" >
              <div class="timeArticle">发表时间: {{ item.create_time.split('T')[0] }}</div>
              <div>{{ item.content }}</div>
              <template #footer>
                <div>
                  <span v-for="path in item.article_imgs.split(',')">
                  <el-image :src="`${user.articleIMG}${path}`" v-if="path !== ''"
                      @click="showBigImg(`${user.articleIMG}${path}`)"   style="width: 100px;height: 100px;margin-right: 10px;" @error="loadError(path)"></el-image>
                </span>
                </div>
                <el-badge :value="item.add_love" class="item" style="margin-right: 40px;margin-top: 10px;"
                          badge-style="font-size:10px;"><span class="iconfont icon-aixin"
                                                              style="font-size: 28px;"></span></el-badge>
                <el-badge :value="item.add_collect" class="item" style="margin-top: 10px;" badge-style="font-size:10px">
                  <span class="iconfont icon-shoucang" style="font-size: 25px;"></span></el-badge>
                <el-popconfirm
                    confirm-button-text="确定"
                    cancel-button-text="取消"
                    :icon="InfoFilled"
                    icon-color="#626AEF"
                    title="你想要删除这篇文章吗?"
                    cancel-button-type="info"
                    @confirm="confirmDelete(item.id)"
                    width="380px"
                    heigth="200px"
                >
                  <template #reference>
                    <span class="delete_article"><el-icon size="24"><Delete/></el-icon></span>
                  </template>
                </el-popconfirm>
                <div class="show_btn" @click.prevent.stop="showDialogVisible(item)"><span
                    class="iconfont icon-xiugai edit_show" style=""></span></div>
              </template>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>

  <el-dialog v-model="user.editDataFormVisible" title="编辑资料" width="500">
    <el-form :model="user.userForm" label-width="80">
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="user.userForm.nickname" style="width: 300px;"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="user.userForm.gender" placeholder="性别" style="width: 300px;">
          <el-option label="男" value="0"/>
          <el-option label="女" value="1"/>
          <el-option label="保密" value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item label="年龄">
        <el-input-number v-model="user.userForm.age" :min="1" :max="60"/>
      </el-form-item>
      <!-- 使用头像上传组件 -->
      <el-form-item label="头像" prop="avatar">
        <!--        <el-upload  class="avatar-uploader" action="#" list-type="picture-card" :auto-upload="false"-->
        <!--                   v-model:file-list="user.avatar" :on-preview="showPreview" drag="true" limit="1">-->
        <el-upload class="avatar-uploader" action="http://api.leleapi.cn:8000/users/avatar/" :on-success="successImg"
                   list-type="picture-card" :auto-upload="true" accept="image/png,image/jpeg,image/jpg,image/webp"
                   v-model:file-list="user.avatar" :on-preview="showPreview" drag="true" limit="1">
          <el-icon>
            <Plus/>
          </el-icon>
        </el-upload>
        <el-dialog v-model="user.uploadDialogVisible">
          <el-image :src="user.avatar[0].url" alt="Preview Image"/>
        </el-dialog>
      </el-form-item>
      <el-form-item label="个性签名" prop="bio">
        <el-scrollbar>
          <el-input type="textarea" :rows="3" v-model="user.userForm.signature" style="width: 300px;"></el-input>
        </el-scrollbar>
      </el-form-item>
      <el-form-item label="是否展示" prop="is_show">
        <el-switch v-model="user.userForm.is_show" active-value="1" inactive-value="0" active-color="#13ce66"
                   inactive-color="#eaecf0">
        </el-switch>
      </el-form-item>
      <el-form-item>
        <div style="margin-left: auto;">
          <el-button @click="user.editDataFormVisible = false">取消</el-button>
          <el-button type="primary" @click="userData">确定</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
  <!--  文章是否显示个人信息-->
  <el-dialog
      v-model="user.showVisible"
      title="警告"
      width="500"
      align-center
  >
    <span>修改文章是否显示个人信息，将会影响到您的点赞和收藏，是否继续？</span>
    <template #footer>
      <div class="dialog-footer">
        <span style="margin-right: 20px;font-weight: bold;">是否展示</span>
        <el-switch v-model="user.articleShow" active-value="1" inactive-value="0" active-color="#13ce66"
                   inactive-color="#eaecf0">
        </el-switch>
        <el-button type="primary" @click="confirmEditIsShow" style="margin-left: 20px;">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.info {
  display: inline-block;
  margin-left: 20px;
}

.nickname {
  font-weight: bold;
  font-size: 20px;
  color: #ffffff;
}

.friends {
  font-size: 16px;

  span {
    color: #ffffff;
    font-size: 20px;
  }
}

.signature {
  font-size: 16px;
}

.edit_info {
  font-size: 16px;
  float: right;
  margin-top: -40px;
}

.show_btn {
  display: inline-block;
  position: relative;
}

.edit_show {
  font-size: 25px;
  margin-left: 70px;
  cursor: pointer;
  display: inline-block;
  position: absolute;
  top: -16px

}

.timeArticle {
  font-size: 12px;
  color: #999999;
  margin-bottom: 10px;
}

.delete_article {
  margin-left: 30px;
  position: absolute;
  bottom: 22px;
  display: inline-block;
  cursor: pointer;
}
</style>